using System.Text.Json;
using Flurl.Http;
using Vin.Extension.Notify.QiyeWechat.Models;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.Core.JsonCategory;

namespace Vin.Extension.Notify.QiyeWechat.Service;

public class QwSendMsgService : VinBaseService
{
    public string GetWebHookUrl(string key) => $"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}";

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="webHookUrl">机器人地址</param>
    /// <param name="msg">消息模型</param>
    /// <returns></returns>
    public async Task<(bool, string)> SendMsgAsync(string webHookUrl, BaseMsgModel msg)
    {
        var result = await webHookUrl.PostStringAsync(msg.ToUnderLineJson()).ReceiveString();
        var data = result.ToJsonNode();
        if (data == null || data.GetValueKind() != JsonValueKind.Object) return (false, result);
        return (data["errcode"]?.GetValue<int>() == 0, data["errmsg"]?.GetValue<string>() ?? result);
    }

    /// <summary>
    /// 发送文本消息
    /// </summary>
    /// <param name="key">机器人的key</param>
    /// <param name="content">内容</param>
    /// <param name="mentionedMobileList">需要@的手机号列表，@all表示提醒所有人</param>
    /// <param name="mentionedList">需要@的userid列表，@all表示提醒所有人</param>
    /// <returns></returns>
    public async Task<(bool, string)> SendTextMessageAsync(string key, string content,
        List<string>? mentionedMobileList = null,
        List<string>? mentionedList = null)
    {
        if (content.Length * 2 > 2048) return (false, "文本消息内容长度不能超过2048个字节");

        var msg = new TextBaseMsgModel(new TextBaseMsgModel.TextContent(content)
        {
            MentionedList = mentionedList,
            MentionedMobileList = mentionedMobileList
        });
        return await SendMsgAsync(GetWebHookUrl(key), msg);
    }

    /// <summary>
    /// 发送markdown消息
    /// </summary>
    /// <param name="key">机器人的key</param>
    /// <param name="content">markdown内容，参考 https://developer.work.weixin.qq.com/document/path/91770#markdown%E7%B1%BB%E5%9E%8B</param>
    /// <returns></returns>
    public async Task<(bool, string)> SendMarkdownMessageAsync(string key, string content,
        List<string>? receivers = null)
    {
        if (content.Length * 2 > 4096) return (false, "markdown消息内容长度不能超过4096个字节");

        var msg = new MarkdownMsgModel(new MarkdownMsgModel.MarkdownContent(content));
        var res = await SendMsgAsync(GetWebHookUrl(key), msg);
        if (receivers?.Count > 0)
        {
            await SendTextMessageAsync(key, "", receivers);
        }

        return res;
    }
}